package com.siberhus.tdfl.excel;

import java.math.BigDecimal;
import java.util.Date;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;

public class DefaultExcelRowReader implements ExcelRowReader {
	
	@Override
	public String[] readRow(Row row) {
		
		return getStringValues(row);
	}
	
	private String[] getStringValues(Row row){
		String values[] = null;
		values = new String[row.getLastCellNum()];
		for(int i=0;i<row.getLastCellNum();i++){
			values[i] = getCellValueAsString(row.getCell(i));
		}
		return values;
	}
	
	private String getCellValueAsString(Cell cell) {
		Object value = getCellValue(cell);
		if (value == null) {
			return null;
		} else if (value instanceof Number) {
			return ObjectUtils.toString(value);
		} else if (value instanceof Date) {			
			return ObjectUtils.toString(ConvertUtils.convert(value, String.class));
		} else {
			return value.toString();
		}
	}
	
	private Object getCellValue(Cell cell) {
		if (cell == null)
			return null;
		switch (cell.getCellType()) {
			case Cell.CELL_TYPE_STRING:
				RichTextString rts = cell.getRichStringCellValue();
				if (rts != null) {
					return rts.getString();
				}
				return null;
			case Cell.CELL_TYPE_NUMERIC:
				String value = cell.toString();
				/*
				 * In POI we cannot know which cell is date or number because both
				 * cells have numeric type To fix this problem we need to call
				 * toString if it's number cell we can parse it but if it's date
				 * cell we cannot parse the value with number parser
				 */
				try {
					return new BigDecimal(value);
				} catch (Exception e) {
					return cell.getDateCellValue();
				}
			case Cell.CELL_TYPE_BLANK:
				return null;
			case Cell.CELL_TYPE_BOOLEAN:
				return cell.getBooleanCellValue();
			case Cell.CELL_TYPE_FORMULA:
				return cell.getCellFormula();
		}
		return null;
	}
	
}
